package com.example.partyfee.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.partyfee.dto.Result;
import com.example.partyfee.dto.SalaryDTO;
import com.example.partyfee.dto.SalaryQueryDTO;
import com.example.partyfee.entity.Salary;
import com.example.partyfee.service.SalaryService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 工资控制器
 */
@RestController
@RequestMapping("/salaries")
@RequiredArgsConstructor
@Validated
public class SalaryController {

    private final SalaryService salaryService;

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> createSalary(@Valid @RequestBody SalaryDTO salaryDTO) {
        salaryService.createSalary(salaryDTO);
        return Result.success();
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> updateSalary(@PathVariable Long id, @Valid @RequestBody SalaryDTO salaryDTO) {
        salaryService.updateSalary(id, salaryDTO);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> deleteSalary(@PathVariable Long id) {
        salaryService.deleteSalary(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<Salary> getSalary(@PathVariable Long id) {
        return Result.success(salaryService.getSalary(id));
    }

    @PostMapping("/import")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<String>> importSalaries(
            @RequestParam("file") MultipartFile file,
            @RequestParam @NotBlank(message = "工资月份不能为空") String salaryMonth
    ) throws IOException {
        List<String> errors = salaryService.importSalariesFromExcel(file, salaryMonth);
        if (errors.isEmpty()) {
            return Result.success("导入成功", null);
        } else {
            return Result.success("导入过程中存在错误", errors);
        }
    }

    @GetMapping
    public Result<IPage<Salary>> getSalaryPage(SalaryQueryDTO queryDTO) {
        return Result.success(salaryService.getSalaryPage(queryDTO));
    }

    @GetMapping("/months")
    public Result<List<String>> getSalaryMonths() {
        return Result.success(salaryService.getSalaryMonths());
    }

    @GetMapping("/export")
    public void exportSalaries(SalaryQueryDTO queryDTO, HttpServletResponse response) throws IOException {
        salaryService.exportSalariesToExcel(queryDTO, response);
    }
} 